var http = require('http');
var querystring = require('querystring');
const cheerio = require('cheerio')
var request = require('request');
var url = require('url');
var fs = require("fs");

function downImg(item,address){
  fs.access(process.cwd()+"/image/马小巧-"+address.code+'-'+address.name+'/'+item.split('/')[item.split('/').length-1], fs.constants.R_OK, (err) => { 
    if (err) {
      var req = http.get(item, function (res) {

        var imgData = "";
      
        res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
      
        res.on("data", function (chunk) {
          imgData += chunk;
        });
      
        res.on("end", function () {
          if (!fs.existsSync(process.cwd()+"/image/马小巧-"+address.code+'-'+address.name)) {
            fs.mkdirSync(process.cwd()+"/image/马小巧-"+address.code+'-'+address.name);
          }
          fs.writeFile(process.cwd()+"/image/马小巧-"+address.code+'-'+address.name+'/'+item.split('/')[item.split('/').length-1], imgData, "binary", function (err) {
            if (err) {
              console.log("保存失败000",err);
            }
            console.log("保存成功");
          });
          
          
        });
      
        res.on("error", function (err) {
      
          console.log("请求失败111",err+":"+address.name + '---' + item);
      
        });
      
      });
      
      req.on('error', function (err) {
      
        console.log("请求失败2222" + err.message+":"+address.name + '---' + item);
      
      });
    }
  }); 
 
  
}

module.exports = downImg;
